package com.example.hms.awareness;

import static android.content.Context.SENSOR_SERVICE;

import android.app.Application;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;

import java.util.List;

public class SensorUtil {
    private static final String TAG = SensorUtil.class.getSimpleName();
    public static boolean isFaceDown = false;
    private SensorManager sensorManager;
    
    public SensorUtil(Application application){
        sensorManager = (SensorManager) application.getSystemService(SENSOR_SERVICE);
    }

    public void start() {
        List<Sensor> sensorList = sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);
        if (sensorList.size() > 0) {
            Sensor accelerometerSensor = sensorList.get(0);
            sensorManager.registerListener(accelerometerListener, accelerometerSensor,
                SensorManager.SENSOR_DELAY_NORMAL);
            Log.d(TAG, "sensor start");
        } else {
            Log.d(TAG, "No accelerometer present!");
        }
    }
    
    private SensorEventListener accelerometerListener = new SensorEventListener() {

        @Override
        public void onAccuracyChanged(Sensor arg0, int arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onSensorChanged(SensorEvent arg0) {
            float z_value = arg0.values[2];
            if (z_value >= 0) {
                // Log.d(TAG, "Face UP");
                isFaceDown = false;
            } else {
                // Log.d(TAG, "Face DOWN");
                isFaceDown = true;
            }
        }
    };
    
    public void stop(){
        sensorManager.unregisterListener(accelerometerListener);
        Log.d(TAG, "sensor stop");
    }
}
